package com.yuncheng.oaApi.weboffice;

import com.yuncheng.annotation.AutoLog;
import com.yuncheng.oaApi.entity.OaWjjl;
import com.yuncheng.oaApi.service.IOaWjjlService;
import com.yuncheng.vo.HttpResult;
import com.yuncheng.oaApi.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "OA-WebOffice在线文档编辑接口")
@RestController
@RequestMapping("/api/spzx-oa/webOfficeApi")
public class OaWebOfficeApi {
    private static final Logger log = LoggerFactory.getLogger(OaWebOfficeApi.class);

    @Resource
    private OaWebOfficeFile oaWebOfficeFIle;

    @Resource
    private IOaWjjlService oaWjjlService;

//    @Resource
//    private ISpcyRsOnlineEditService spcyRsOnlineEditService;

//    @Resource
//    private HnCaUtils hnCaUtils;

    @AutoLog(value = "将在线文档转为Pdf文档并保存")
    @ApiOperation(value = "将在线文档转为Pdf文档并保存")
    @ApiImplicitParam(name = "id",value = "文件id")
    @GetMapping(value = "getDocxToPdf")
    public HttpResult<?> getDocxToPdf(@RequestParam("id") String id){
        OaWjjl wjjl = oaWjjlService.getById(id);
        if (wjjl == null){
            return HttpResult.error("文件不存在");
        }
        if (StringUtils.isNotBlank(wjjl.getFwjlx()) && wjjl.getFwjlx().equals(".pdf")){
            return HttpResult.error("当前文件已经是pdf无法再次生成，请重新编辑文档");
        }

        // 关闭文档
        Result closeResult1 = oaWebOfficeFIle.closeFile(id);
        if (!closeResult1.isSuccess()){
            return HttpResult.error(closeResult1.getMessage());
        }

        // 将在线文档转pdf
        Result result = oaWebOfficeFIle.getDocxToPdfFile(wjjl, wjjl.getFwjccmc());
        if (!result.isSuccess()){
            return HttpResult.error(result.getMessage());
        }

        // 关闭文档
        return HttpResult.ok("转换成功");
    }

//    @AutoLog(value = "将在线文档转为Pdf文档并保存和盖章")
//    @ApiOperation(value = "将在线文档转为Pdf文档并保存和盖章")
//    @ApiImplicitParam(name = "id",value = "文件id")
//    @GetMapping(value = "getDocxToPdfAndGz")
//    public HttpResult<?> getDocxToPdfAndGz(@RequestParam("id") String id){
//        OaWjjl wjjl = oaWjjlService.getById(id);
//        if (wjjl == null){
//            return HttpResult.error("文件不存在");
//        }
//        if (StringUtils.isNotBlank(wjjl.getFwjlx()) && wjjl.getFwjlx().equals(".pdf")){
//            return HttpResult.error("当前文件已经是pdf无法再次生成，请重新编辑文档");
//        }
//
//        // 关闭文档
//        Result closeResult1 = webOfficeFIle.closeFile(id);
//        if (!closeResult1.isSuccess()){
//            return HttpResult.error(closeResult1.getMessage());
//        }
//
//        // 将在线文档转pdf
//        Result result = webOfficeFIle.getDocxToPdfFile(wjjl, wjjl.getFcflj());
//        if (!result.isSuccess()){
//            return HttpResult.error(result.getMessage());
//        }
//
//        HttpResult<?> httpResult = hnCaUtils.fileCaByGJZ(id);// 盖章
//        if (!httpResult.isSuccess()){
//            return HttpResult.error(httpResult.getMessage());
//        }
//
//        // 关闭文档
//        return HttpResult.ok("转换成功");
//    }

    @AutoLog(value = "将word文件关闭并保存")
    @ApiOperation(value = "将word文件关闭并保存")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id",value = "文件id",required = true),
            @ApiImplicitParam(name = "isClose",value = "是否关闭文档，true=【关闭】")
    })
    @GetMapping(value = "getWebOfficeDownloadFile")
    public HttpResult<?> getWebOfficeDownloadFile(@RequestParam("id") String id,
                                                  @RequestParam(value = "isClose",defaultValue = "false") boolean isClose){
        boolean isDel = false;
        OaWjjl wjjl = oaWjjlService.getById(id);
        if (wjjl == null){
            return HttpResult.error("文件不存在");
        }
        if (StringUtils.isNotBlank(wjjl.getFwjlx()) && wjjl.getFwjlx().equals(".pdf")){
            return HttpResult.ok("保存关闭成功");
        }

        // 关闭文档
        Result closeResult1 = oaWebOfficeFIle.closeFile(id);
        if (!closeResult1.isSuccess()){
            return HttpResult.error(closeResult1.getMessage());
        }

        oaWebOfficeFIle.getWebOfficeDownloadFile2(wjjl, wjjl.getFcfljxn(), isDel);

        // 关闭文档
        if (isClose) {
            return HttpResult.ok("保存关闭成功");
        }else {

            return HttpResult.ok("保存成功");
        }

    }

    @AutoLog(value = "打开在线文档")
    @ApiOperation(value = "打开在线文档")
    @ApiImplicitParam(name = "id",value = "文件id")
    @GetMapping(value = "openFile")
    public HttpResult<?> openFile(@RequestParam("id") String id){
        OaWjjl wjjl = oaWjjlService.getById(id);
        if (wjjl == null){
            return HttpResult.error("文件不存在");
        }
        if (StringUtils.isNotBlank(wjjl.getFwjlx()) && wjjl.getFwjlx().equals(".pdf")){
            return HttpResult.error("当前文档为pdf文档，请选择重新编辑文档");
        }
        String url = oaWebOfficeFIle.openFile(wjjl,wjjl.getId(),wjjl.getFcfljxn());
        Map resultMap = new HashMap();
        resultMap.put("wordUrl",url);
        return HttpResult.ok(resultMap);
    }

    @AutoLog(value = "删除在线文档")
    @ApiOperation(value = "删除在线文档")
    @ApiImplicitParam(name = "id",value = "文件id")
    @GetMapping(value = "deleteFile")
    public HttpResult<?> deleteFile(String id){
        OaWjjl wjjl = oaWjjlService.getById(id);
        if (wjjl == null){
            return HttpResult.error("文件不存在");
        }
        oaWebOfficeFIle.deleteFile(wjjl.getFcfljxn());
        return HttpResult.ok("删除成功");
    }

    @AutoLog(value = "重新编辑Pdf文档")
    @ApiOperation(value = "重新编辑Pdf文档")
    @ApiImplicitParam(name = "id",value = "文件id")
    @GetMapping(value = "againEditPdfOnlineFile")
    public HttpResult<?> againEditPdfOnlineFile(@RequestParam("id") String id){
        if (StringUtils.isBlank(id)){
            log.error("文件参数不能为空");
            return HttpResult.error("文件参数不能为空");
        }
        OaWjjl wjjl = oaWjjlService.getById(id);
        if (wjjl == null){
            log.error("文件记录不存在");
            return HttpResult.error("文件记录不存在");
        }
        boolean isFlag = oaWebOfficeFIle.againEditPdfOnlineFile(wjjl);// 修改文件
        if (isFlag){
            String url = oaWebOfficeFIle.openFile(wjjl,wjjl.getId(),wjjl.getFcfljxn());
            Map resultMap = new HashMap();
            resultMap.put("wordUrl",url);
            return HttpResult.ok(resultMap);
        }else {
            return HttpResult.error("重新编辑失败，请刷新重试");
        }
    }

//    @AutoLog(value = "用户在线编辑类型切换")
//    @ApiOperation(value = "用户在线编辑类型切换")
//    @ApiImplicitParam(name = "ftype",value = "在线编辑模式（包含分为[客户端模式]、[服务端模式]、默认为【客户端模式】）")
//    @GetMapping(value = "onlineTypeSwitch")
//    public HttpResult<?> onlineTypeSwitch(@RequestParam(value = "ftype",defaultValue = "")String ftype){
//        CurrentUserVo currentUser = ThreadContextHelper.getCurrentUser();
//        if (currentUser == null){
//            return HttpResult.error("登录已失效，请重新登录");
//        }
//
//        String userid = currentUser.getId();
//        HttpResult httpResult = new HttpResult();
//
//        List<SpcyRsOnlineEdit> userList = spcyRsOnlineEditService.list(new LambdaQueryWrapper<SpcyRsOnlineEdit>()
//                .eq(StringUtils.isNotBlank(userid), SpcyRsOnlineEdit::getFuserid, userid));
//
//        SpcyRsOnlineEdit oldOnlineEdit = null;
//        String oldType = "";
//        if (CollectionUtils.isNotEmpty(userList)){
//            oldOnlineEdit = userList.get(0);
//            oldType = userList.get(0).getFtype();
//
//            if (oldOnlineEdit != null){
//                if (StringUtils.isNotBlank(ftype) && StringUtils.isNotBlank(oldType) && !ftype.equals(oldType)) {
//                    oldOnlineEdit.setFtype(ftype);
//                    spcyRsOnlineEditService.updateById(oldOnlineEdit);
//                }
//            }
//            if (StringUtils.isBlank(ftype)){
//                httpResult.setResult(oldType);
//
//                StringBuffer msg = new StringBuffer("初始化成功，当前在线编辑模式");
//                msg.append("为[").append(oldType).append("]");
//                httpResult.setMessage(msg.toString());
//            }else {
//                if (ftype.equals(oldType)){
//                    httpResult.setResult(oldType);
//
//                    StringBuffer msg = new StringBuffer("初始化成功，当前在线编辑模式");
//                    msg.append("为[").append(oldType).append("]");
//                    httpResult.setMessage(msg.toString());
//                }else {
//                    httpResult.setResult(ftype);
//
//                    StringBuffer msg = new StringBuffer("切换成功，将在线编辑模式");
//                    msg.append("从[").append(oldType).append("]切换为").append("[").append(ftype).append("]");
//                    httpResult.setMessage(msg.toString());
//                }
//            }
//
//        }else {
//            if (StringUtils.isBlank(ftype)){
//                ftype = "客户端模式";
//            }
//            SpcyRsOnlineEdit onlineEdit = new SpcyRsOnlineEdit();
//            onlineEdit.setId(GetUuIdUtils.ReplaceUuId());
//            onlineEdit.setFtype(ftype);
//            onlineEdit.setFuserid(userid);
//            spcyRsOnlineEditService.save(onlineEdit);
//
//            StringBuffer msg = new StringBuffer("初始化成功，将在线编辑模式");
//            msg.append("初始化为[").append(ftype).append("]");
//            httpResult.setMessage(msg.toString());
//            httpResult.setResult(ftype);
//        }
//        httpResult.setSuccess(true);
//        return httpResult;
//    }


    //    @AutoLog(value = "将本地文件上传到在线文档")
//    @ApiOperation(value = "将本地文件上传到在线文档")
//    @ApiImplicitParam(name = "id",value = "文件id")
//    @GetMapping(value = "WebOfficeUploadFile")
    public HttpResult<?> WebOfficeUploadFile(String id){
        OaWjjl wjjl = oaWjjlService.getById(id);
        if (wjjl == null){
            return HttpResult.error("文件不存在");
        }
        Result result = oaWebOfficeFIle.uploadWebOfficeFile(wjjl,wjjl.getFwjccmc(), wjjl.getFcfljxn());
        if (!result.isSuccess()){
            return HttpResult.error(result.getMessage());
        }
        return HttpResult.ok("上传成功");
    }

    //    @AutoLog(value = "判断在线文档是否已经打开")
//    @ApiOperation(value = "判断在线文档是否已经打开")
//    @ApiImplicitParam(name = "id",value = "文件id")
//    @GetMapping(value = "isOpenFile")
    public HttpResult<?> isOpenFile(String id){
        OaWjjl wjjl = oaWjjlService.getById(id);
        if (wjjl == null){
            return HttpResult.error("文件不存在");
        }
        boolean openFile = oaWebOfficeFIle.isOpenFile(wjjl.getId());
        if (openFile){
            return HttpResult.error("文档已打开");
        }
        return HttpResult.ok("文档未打开");
    }

    //    @AutoLog(value = "关闭在线文档")
//    @ApiOperation(value = "关闭在线文档")
//    @ApiImplicitParam(name = "id",value = "文件id")
//    @GetMapping(value = "closeFile")
    public HttpResult<?> closeFile(String id){
        OaWjjl wjjl = oaWjjlService.getById(id);
        if (wjjl == null){
            return HttpResult.error("文件不存在");
        }
        Result result = oaWebOfficeFIle.closeFile(wjjl.getId());
        if (!result.isSuccess()){
            return HttpResult.error(result.getMessage());
        }
        return HttpResult.ok("关闭成功");
    }
}
